package com.cheetah.es.web;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cheetah.es.entity.Position;
import com.cheetah.es.mapper.PositionMapper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/position")
public class PositionController {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private PositionMapper positionMapper;

    /**
     * 初始化索引导入
     * @return
     */
    @RequestMapping("/indexAll")
    public Object indexAll() {
        List<Position> list =
                this.positionMapper.selectList(new QueryWrapper<>());
        list.forEach(position -> {
            try {
                client.index(new IndexRequest("lagou_job")
                        .source(JSON.toJSONString(position), XContentType.JSON), RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return 1;
    }

    /**
     * 用来测试集群的
     * @return
     */
    @RequestMapping("/indexAsync")
    public Object indexAsync() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Position> list = positionMapper.selectList(new QueryWrapper<>());
                list.forEach(position -> {
                    System.out.println(position.getId());
                    try {
                        client.index(new IndexRequest("lagou_job")
                                .source(JSON.toJSONString(position), XContentType.JSON), RequestOptions.DEFAULT);
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        }).start();

        return 1;
    }

    /**
     * 执行搜索
     * @param name
     * @return
     * @throws Exception
     */
    @RequestMapping("/search")
    public Object search(String name) throws Exception {
        SearchHits hits = searchHit(QueryBuilders.matchQuery("positionName", name), -1);
        long value = hits.getTotalHits().value;
        List result = hitsList(hits);
        if (value >=5) {
            return result;
        }
        int limit = (int) (5-value);
        hits = searchHit(QueryBuilders.matchQuery("positionAdvantage", "美女"), limit);
        result.addAll(hitsList(hits));

        return result;
    }

    /**
     * 根据id查找
     * @return
     */
    @RequestMapping("/get")
    public Object get() {

        List<Position> list =
                this.positionMapper.selectList(new QueryWrapper<>());
        list.forEach(position -> {
            try {
                SearchHits hits = searchHit(QueryBuilders.termQuery("id", position.getId()), 1);
                System.out.println(hits.getTotalHits().value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return null;
    }

    List hitsList(SearchHits hits) {
        List result = new ArrayList();
        hits.forEach(item-> result.add(item.getSourceAsMap()));
        return result;
    }

    SearchHits searchHit(QueryBuilder query, int size) throws Exception {
        SearchSourceBuilder source = new SearchSourceBuilder().query(query);
        if (size > 0) {
            source.size(size);
        }
        return this.client.search(new SearchRequest("lagou_job")
                        .source(source), RequestOptions.DEFAULT).getHits();
    }
}
